//
//  NewTravelNoteViewController.m
//  TravelFollowYourHeart
//
//  Created by ENERGY on 2017/12/19.
//  Copyright © 2017年 Lwx. All rights reserved.
//

#import "DraftEditViewController.h"
#import "IWTextView.h"
#import <CoreLocation/CoreLocation.h>
#import "ZYQAssetPickerController.h"
#import "SelectPicCollectionViewCell.h"
#import "AddressSelectedController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>

#import "MyTravelViewController.h"
#import "DraftEditCell.h"
#import "TZImagePickerController.h"
#import "UIPlaceHolderTextView.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import "DraftModel.h"
static NSString * const amapServiceKey = @"9fa9446d3fd67ff580e4694ed3e5aa6a";

#define TopViewH 50
#define Border 10
#define imageW (SCREEN_WIDTH - 5 * Border)/4
#define bottomBarH 50
@interface DraftEditViewController ()<CLLocationManagerDelegate, ZYQAssetPickerControllerDelegate, UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource, MJPhotoBrowserDelegate>
@property (nonatomic, strong)UIView * topView;
@property (nonatomic, strong)UITextField * titleTextField;
@property (nonatomic, strong)UIView * middleView;
//@property (nonatomic, strong)IWTextView * contentTextView;
@property (nonatomic, strong)UIButton * cameraBtn;
@property (nonatomic, strong)UIView * bottomView;
@property (nonatomic, strong)UIButton * locationBtn;
//@property (nonatomic, strong)UIImagePickerController *imagePicker;
@property (nonatomic, strong)CLLocationManager * locationManager;
@property (nonatomic, strong)UIView * bottomBarView;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)UILabel * locationLab;

@property (nonatomic,strong) NSMutableArray *dataArray; //数据源
@property (nonatomic,strong) NSMutableArray *dataImageArray; // 存储选择的图片（二进制）
@property (nonatomic,strong) NSMutableArray *dataImageWithStrArray; // 上传图片返回的图片地址
@property (nonatomic,strong) NSData *imageWithData;

@property (nonatomic, strong)UIAlertController * alertController;
@property (nonatomic, strong)TZImagePickerController * imagePicker;
@property (nonatomic, strong)UIImagePickerController * imagePickerController;
@property (nonatomic,strong)NSMutableDictionary *objdic;

@property (nonatomic, strong)NSMutableArray * pickImageArray;//相册修改的图片
@property (nonatomic, strong)NSMutableArray * transferArray;
@property (nonatomic, strong)NSMutableArray * draftImageArray;//后台传过来的图片数组
@property (nonatomic, strong)UIPlaceHolderTextView * contentTextView;
@property (nonatomic, strong)DraftModel * draftModel;
@property (nonatomic, strong)NSMutableArray * compareArra;//最后比较数组
@property (nonatomic, strong)NSString * delStr;
@property (nonatomic, assign)int state;
@end

@implementation DraftEditViewController(Networking)
- (void)getDraftData{
    NSDictionary * dic = @{
                           @"did":self.travelID
                           };
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/diary/editDetail") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
        }else{
            if ([obj[@"code"] integerValue] == 100000){
                self.titleTextField.text = obj[@"data"][@"title"];
                if (obj[@"data"][@"content"]) {
                    self.contentTextView.placeholder = nil;
                }
                self.draftModel = [DraftModel yy_modelWithDictionary:obj[@"data"]];
                self.contentTextView.text = self.draftModel.content;
                self.locationLab.text = self.draftModel.location;
                [self.transferArray addObjectsFromArray:self.draftModel.pic];
                [self.transferArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ((![obj isEqualToString:@""]) || (!([obj length] == 0))) {
                        [self.draftImageArray addObject:obj];
                        [self.compareArra addObject:obj];
                    }
                }];

                [self.collectionView reloadData];
            }else{
                [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
            }
        }
    }];
}

- (void)upDataTravelNote{
    NSDictionary * dic = @{
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"did":@([self.travelID intValue]),
                           @"state":@(self.state),
                           @"title":self.titleTextField.text,
                           @"content":self.contentTextView.text,
                           @"location":self.locationLab.text,
                           @"lng":@([LocationTool shareIntance].longitude),
                           @"lat":@([LocationTool shareIntance].latitude)
//                           @"del":self.delStr
                           };
    [self showprogressHUD];
    [[HttpRequest shardWebUtil]postNetworkRequestURLString:Url(@"/diary/updateDiaryMove") andParas:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        if (self.draftImageArray.count == 0) {
            [self.pickImageArray removeLastObject];
        }else{
            [self.pickImageArray removeLastObject];
            for (int i = 0; i<self.draftImageArray.count; i++) {
                NSData *data = [NSData  dataWithContentsOfURL:[NSURL URLWithString:self.draftImageArray[i]]];
                UIImage *image =  [UIImage imageWithData:data];
                [self.pickImageArray addObject:image];
            }
        }
        for (int i = 0; i<self.pickImageArray.count; i++) {
            UIImage *img = self.pickImageArray[i];
            NSData *data = UIImageJPEGRepresentation(img, .5);
            [formData appendPartWithFileData:data name:@"pic[]" fileName:[NSString stringWithFormat:@"%d%ld.jpg",i,data.length] mimeType:@"image/jpeg"];
        }
    } andTransferGottenData:^(id obj, NSError *error) {
        [self hiddenProgressHUD];
        if (error)
        {
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }
        else
        {
            if ([obj[@"code"] integerValue] == 100000) {
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
//                [self.navigationController popViewControllerAnimated:YES];
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[MyTravelViewController class]]) {
                        MyTravelViewController *vc = (MyTravelViewController *)controller;
                        vc.isPublish = NO;
                        [self.navigationController popToViewController:vc animated:YES];
                    }
                }
            }else{
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}

@end

@implementation DraftEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.view.backgroundColor = getColor(@"e5e5e5");
    
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.titleTextField];
    [self.view addSubview:self.middleView];
    
    [self.middleView addSubview:self.contentTextView];
    [self.middleView addSubview:self.collectionView];
    [self.middleView addSubview:self.cameraBtn];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.locationBtn];
    [self.bottomView addSubview:self.locationLab];
    [self.view addSubview:self.bottomBarView];
    [self getDraftData];
    //配置高德地图
    [AMapServices sharedServices].apiKey = amapServiceKey;
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)uploadDelString{
    for (int i = 0; i<self.compareArra.count; i++) {
        for (int j = 0; j<self.draftImageArray.count; j++) {
            if (self.compareArra[i] == self.draftImageArray[j]) {
                [self.compareArra removeObject:self.compareArra[i]];
            }
        }
    }
     self.delStr = [self.compareArra componentsJoinedByString:@","];
}

#pragma init
- (UIView *)topView{
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, TopViewH)];
        _topView.layer.cornerRadius = 8;
        _topView.layer.masksToBounds = YES;
        _topView.backgroundColor = [UIColor whiteColor];
    }return _topView;
}

- (UITextField *)titleTextField{
    if (!_titleTextField) {
        _titleTextField = [[UITextField alloc] initWithFrame:CGRectMake(Border, 0, SCREEN_WIDTH - 2 * Border, 50)];
        _titleTextField.font = [UIFont systemFontOfSize:14.0];
        _titleTextField.placeholder = @"输入标题内容";
    }return _titleTextField;
}

- (UIView *)middleView{
    if (!_middleView) {
        _middleView = [[UIView alloc] init];
        _middleView.frame = CGRectMake(0, self.topView.bottom + Border, SCREEN_WIDTH, 250);
        _middleView.backgroundColor = [UIColor whiteColor];
        _middleView.layer.cornerRadius = 8;
        _middleView.layer.masksToBounds = YES;

    }return _middleView;
}

- (UITextView *)contentTextView{
    if (!_contentTextView) {
        _contentTextView = [[UIPlaceHolderTextView alloc]initWithFrame:CGRectMake(Border, Border, SCREEN_WIDTH - 2 * Border, self.middleView.height - 3 * Border - 100)];
        _contentTextView.backgroundColor = [UIColor whiteColor];
//        _contentTextView.placeholder = @"请输入您要评论的内容";
        _contentTextView.font = [UIFont systemFontOfSize:14.0];
    }return _contentTextView;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        int cellW = (SCREEN_WIDTH - 4 * Border)/3;
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(cellW, cellW);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(Border, self.contentTextView.bottom + Border, SCREEN_WIDTH - 2*Border, (SCREEN_WIDTH - 5 * Border)/4) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = NO;
        _collectionView.backgroundColor = [UIColor clearColor];

        [_collectionView registerClass:[DraftEditCell class] forCellWithReuseIdentifier:NSStringFromClass([DraftEditCell class])];
    }return _collectionView;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        _bottomView.layer.cornerRadius = 8;
        _bottomView.layer.masksToBounds = YES;
        _bottomView.frame = CGRectMake(0, self.middleView.bottom + Border, SCREEN_WIDTH, self.topView.height);
    }return _bottomView;
}

- (UIView *)bottomBarView{
    if (!_bottomBarView) {
        _bottomBarView = [[UIView alloc] init];
        _bottomBarView.frame = CGRectMake(0, SCREEN_HEIGHT - 64 - 49, SCREEN_WIDTH, bottomBarH);
        UIButton * surePublishBtn = [[UIButton alloc] init];
        [surePublishBtn setTitle:@"确认发布" forState:UIControlStateNormal];
        surePublishBtn.titleLabel.font = DEF_FontSize_14;
        [surePublishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [surePublishBtn setBackgroundColor:getColor(@"ffbb02")];
        surePublishBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH / 2, bottomBarH);
        [surePublishBtn addTarget:self action:@selector(surePublishBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBarView addSubview:surePublishBtn];
        
        UIButton * draftBtn = [[UIButton alloc] init];
        [draftBtn setTitle:@"存草稿箱" forState:UIControlStateNormal];
        draftBtn.titleLabel.font = DEF_FontSize_14;
        [draftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [draftBtn setBackgroundColor:getColor(@"ffbb02")];
        draftBtn.frame = CGRectMake(SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, bottomBarH);
        [draftBtn addTarget:self action:@selector(draftBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBarView addSubview:draftBtn];
        
        UIView * lineView = [[UIView alloc] init];
        lineView.backgroundColor = [UIColor whiteColor];
        lineView.frame = CGRectMake(SCREEN_WIDTH / 2, 5, 1, bottomBarH - 5 * 2);
        [_bottomBarView addSubview:lineView];
    }return _bottomBarView;
}

- (UIButton *)locationBtn{
    if (!_locationBtn) {
        _locationBtn = [[UIButton alloc] init];
        _locationBtn.frame = CGRectMake(Border, Border, 85, self.bottomView.height - 2 * Border);
        [_locationBtn setImage:[UIImage imageNamed:@"yj_location"] forState:UIControlStateNormal];
        [_locationBtn setTitle:@"所在位置" forState:UIControlStateNormal];
        [_locationBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _locationBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
        [_locationBtn addTarget:self action:@selector(locationBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
    }return _locationBtn;
}

- (UILabel *)locationLab{
    if (!_locationLab) {
        _locationLab = [[UILabel alloc] init];
        _locationLab.font = DEF_FontSize_14;
        _locationLab.textColor = [UIColor blackColor];
        _locationLab.textAlignment = NSTextAlignmentLeft;
        _locationLab.frame = CGRectMake(self.locationBtn.right, Border, SCREEN_WIDTH - Border - self.locationBtn.right, self.bottomView.height - 2 * Border);
    }return _locationLab;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (NSMutableArray *)dataImageArray
{
    if (!_dataImageArray) {
        _dataImageArray = [NSMutableArray array];
    }
    return _dataImageArray;
}

- (NSMutableArray *)compareArra
{
    if (!_compareArra) {
        _compareArra = [NSMutableArray array];
    }
    return _compareArra;
}

- (NSMutableArray *)transferArray
{
    if (!_transferArray) {
        _transferArray = [NSMutableArray array];
    }
    return _transferArray;
}

- (NSMutableArray *)dataImageWithStrArray
{
    if (!_dataImageWithStrArray) {
        _dataImageWithStrArray = [NSMutableArray array];
    }
    return _dataImageWithStrArray;
}

#pragma action
- (void)transformPicture{
    NSLog(@"传照片");
}

- (void)surePublishBtnClick{
    NSLog(@"确认发布");
    self.state = 1;
    [self uploadDelString];
//    [self upDataTravelNote];
    if (self.pickImageArray.count + self.draftImageArray.count == 1) {
        [[HUDHelper sharedInstance] tipMessage:@"请选择图片"];
        return;
    }
    [self upDataTravelNote];
}

- (void)draftBtnClick{
    NSLog(@"存草稿箱");
    self.state = 2;
    [self uploadDelString];
//    [self upDataTravelNote];
    if (self.draftImageArray.count == 0 && self.pickImageArray.count == 1) {
        [[HUDHelper sharedInstance] tipMessage:@"请选择图片"];
        return;
    }
    [self upDataTravelNote];
}

- (void)locationBtnClick{
    AddressSelectedController * addressSelectedVC = [[AddressSelectedController alloc] init];
    addressSelectedVC.completeBlock = ^(DDLocationReGeocode *reGeocode, NSError *error) {
        
        NSLog(@"%@,%@,%f,%f",reGeocode.name,reGeocode.address,reGeocode.coordinate.latitude,reGeocode.coordinate.longitude);
        self.locationLab.text = reGeocode.name;
    };
    addressSelectedVC.currentCoordinate = CLLocationCoordinate2DMake([LocationTool shareIntance].latitude,[LocationTool shareIntance].longitude);
    [self.navigationController pushViewController:addressSelectedVC animated:YES];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.titleTextField resignFirstResponder];
    [self.contentTextView resignFirstResponder];
}

-(NSMutableArray *)pickImageArray
{
    if (!_pickImageArray) {
        _pickImageArray = [NSMutableArray arrayWithArray:@[[UIImage imageNamed:@"fankui"]]];
    }
    return _pickImageArray;
}

-(NSMutableArray *)draftImageArray
{
    if (!_draftImageArray) {
        _draftImageArray = [NSMutableArray array];
    }
    return _draftImageArray;
}

-(UIImagePickerController *)imagePickerController
{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

-(UIAlertController *)alertController
{
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从图库选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            _imagePicker = [[TZImagePickerController alloc]initWithMaxImagesCount:3 - self.draftImageArray.count delegate:self];
            _imagePicker.allowPickingVideo = NO;
            
            _imagePicker.allowTakePicture = NO;
            [self presentViewController:_imagePicker animated:YES completion:nil];
        }];
        UIAlertAction *addPhoneAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePickerController animated:YES completion:nil];
            }
            else
            {
                //  [self showMessage:@"当前设备无摄像头，请从相册获取"];
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [photoAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [addPhoneAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [cancelAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [_alertController addAction:photoAction];
        [_alertController addAction:addPhoneAction];
        [_alertController addAction:cancelAction];
        
    }
    return _alertController;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.pickImageArray.count + self.draftImageArray.count< 4) {
        return self.pickImageArray.count + self.draftImageArray.count;
    }
    return 3;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DraftEditCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([DraftEditCell class]) forIndexPath:indexPath];
    if (indexPath.row < self.draftImageArray.count) {
        [cell.imageView sd_setImageWithURL:self.draftImageArray[indexPath.row]];
    }else{
        cell.imageView.image = self.pickImageArray[indexPath.row - self.draftImageArray.count];
    }
    cell.block = ^(){
        if (indexPath.row+1 > self.draftImageArray.count) {
            if (self.draftImageArray.count > indexPath.row) {
                [self.draftImageArray removeObjectAtIndex:indexPath.row + 1 - self.draftImageArray.count];
            }else{
                if (!self.draftImageArray) {
                    [self.draftImageArray removeObjectAtIndex:indexPath.row];
                }
                
                UIImage *image = self.pickImageArray[indexPath.row];
                [self.pickImageArray removeObject:image];
            }
            [self.collectionView reloadData];
        }else{
            [self.draftImageArray removeObjectAtIndex:indexPath.row];
            [self.collectionView reloadData];
        }
        
    };
    
    if (self.pickImageArray.count + self.draftImageArray.count == indexPath.row + 1) {
        cell.deleteBtn.hidden = YES;
    }
    else
    {
        cell.deleteBtn.hidden = NO;
    }

    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.pickImageArray.count + self.draftImageArray.count == indexPath.row +1) {
        [self presentViewController:self.alertController animated:YES completion:nil];
        return;
    }
}

#pragma mark - MJPhotoBrowserDelegate

-(void)photoBrowser:(MJPhotoBrowser *)photoBrowser didDeletePhotoAtIndex:(NSInteger)index
{
    if (index < self.pickImageArray.count) {
        UIImage *image = self.pickImageArray[index];
        [self.pickImageArray removeObject:image];
        [self.collectionView reloadData];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (self.pickImageArray.count >=4) {
        [[HUDHelper sharedInstance] tipMessage:@"您最多选择3张照片"];
        return;
    }
    [self.pickImageArray insertObject:image atIndex:self.pickImageArray.count - 1];
    [_collectionView reloadData];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos
{
    if (self.pickImageArray.count + photos.count > 4) {
        [[HUDHelper sharedInstance] tipMessage:@"您最多选择3张照片"];
        return;
    }
    [self.pickImageArray removeObjectAtIndex:self.pickImageArray.count - 1];
    [self.pickImageArray addObjectsFromArray:photos];
    [self.pickImageArray addObject:[UIImage imageNamed:@"fankui"]];
    
    [_collectionView reloadData];
}

@end

